package com.Atao.service.impl;

import com.Atao.mapper.AiMapper;
import com.Atao.pojo.AiMessage;
import com.Atao.pojo.AiPhotos;
import com.Atao.service.AiService;
import com.Atao.service.FileDelete;
import com.Atao.utils.AliOssUtil;
import com.Atao.utils.ThreadLocalUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.Atao.utils.getIdUtil;


@Service
public class AiServiceImpl implements AiService {
    @Autowired
    private AiMapper aiMapper;

    @Autowired
    private FileDelete fileDelete;

    /**
     * 添加消息
     * @param uMessage
     * @param aMessage
     */
    @Override
    public void addMessage(String uMessage, String aMessage) {
        AiMessage aiMessage = new AiMessage();
        aiMessage.setUserMessage(uMessage);
        aiMessage.setAiMessage(aMessage);

        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        aiMessage.setUserId(userId);
        aiMapper.add(aiMessage);
    }

    @Override
    public void addStreamMessage(String uMessage, String aMessage) {
        AiMessage aiMessage = new AiMessage();
        aiMessage.setUserMessage(uMessage);
        aiMessage.setAiMessage(aMessage);
        Integer userId = getIdUtil.getId();
        aiMessage.setUserId(userId);
        aiMapper.add(aiMessage);
    }

    @Override
    public List<String> list() {
        Integer userId=getIdUtil.getId();
        List<String> resultList = new ArrayList<>();
        for (AiMessage aiMessage : aiMapper.list(userId)) {
            resultList.add("在时间为"+aiMessage.getCreateTime()+"的对话如下，"+"用户消息："+aiMessage.getUserMessage()+"。你的回答："+aiMessage.getAiMessage()+"。");
        }

        return resultList;
    }

    @Override
    public List<AiMessage> mList() {
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        return aiMapper.list(userId);
    }

    @Override
    public String addPhoto(String prompt, String url) {
        String resultUrl="";
        AiPhotos aiPhotos = new AiPhotos();
        aiPhotos.setUserMessage(prompt);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. 下载图片
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);

            // 2. 获取输入流
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();

            // 3. 获取 Content-Type 并提取文件扩展名
            String contentType = entity.getContentType().getValue();
            String fileExtension = getFileExtensionFromContentType(contentType);

            String filename =UUID.randomUUID().toString()+fileExtension;

            // 4. 上传到 OSS
            resultUrl = AliOssUtil.uploadFile(filename, inputStream);

            // 设置图片 URL
            aiPhotos.setUrl(resultUrl);
        } catch (Exception e) {
            throw new RuntimeException("操作失败: " + e.getMessage());
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        aiPhotos.setUserId(userId);
        aiMapper.addPhoto(aiPhotos);

        return resultUrl;
    }



    // 辅助方法：根据 Content-Type 获取文件扩展名
    private String getFileExtensionFromContentType(String contentType) {
        switch (contentType) {
            case "image/jpeg":
                return ".jpg";
            case "image/png":
                return ".png";
            case "image/gif":
                return ".gif";
            default:
                return ".unknown";
        }
    }

    @Override
    public List<String> pList() {
        Integer userId=getIdUtil.getId();
        List<String> resultList = new ArrayList<>();
        for (AiPhotos aiPhotos : aiMapper.photoList(userId)) {
            resultList.add("在时间为"+aiPhotos.getCreateTime()+"的用户的提示词如下，"+aiPhotos.getUserMessage()+"。");
        }
        return resultList;
    }

    @Override
    public List<AiPhotos> photoList() {
        Integer userId = getIdUtil.getId();
        return aiMapper.photoList(userId);
    }

    @Override
    public void deleteMessages() {
        Integer userId = getIdUtil.getId();
        aiMapper.deleteMessages(userId);
    }

    @Override
    public void deletePhotos() {
        Integer userId = getIdUtil.getId();

        // 提取所有文件地址
        List<AiPhotos> aiPhotos = aiMapper.photoList(userId);

        // 提取文件名并存储到 List<String> 集合中
        List<String> fileUrls = new ArrayList<>();

        for (AiPhotos aiPhoto : aiPhotos) {
            if (aiPhoto.getUrl() != null && !aiPhoto.getUrl().isEmpty()) {
                // 提取文件名部分
                String url = aiPhoto.getUrl();
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                fileUrls.add(fileName);
            }
        }

        // 调用批量删除方法
        fileDelete.deleteFiles(fileUrls);

        // 删除数据库记录
        aiMapper.deletePhotos(userId);
    }

}
